<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="springboot-step-by-step,">










<meta name="description" content="本文为《一步一步学习Spring Boot 2》的第五章的学习笔记，主要内容为SpringBoot事务支持 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 本文部分内容和图片引用自：https://blog.csdn.net/huangwenyi1010/article/details/82810252 源代码地址：https://gitee.com">
<meta name="keywords" content="springboot-step-by-step">
<meta property="og:type" content="article">
<meta property="og:title" content="【第五章】一步一步学习SpringBoot2——SpringBoot事务支持">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/07/18/spring-boot-step-by-step-three/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为《一步一步学习Spring Boot 2》的第五章的学习笔记，主要内容为SpringBoot事务支持 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 本文部分内容和图片引用自：https://blog.csdn.net/huangwenyi1010/article/details/82810252 源代码地址：https://gitee.com">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190724183626414.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190724184038864.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725054936997.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725055301760.jpg">
<meta property="og:updated_time" content="2019-07-24T21:54:20.954Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第五章】一步一步学习SpringBoot2——SpringBoot事务支持">
<meta name="twitter:description" content="本文为《一步一步学习Spring Boot 2》的第五章的学习笔记，主要内容为SpringBoot事务支持 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 本文部分内容和图片引用自：https://blog.csdn.net/huangwenyi1010/article/details/82810252 源代码地址：https://gitee.com">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190724183626414.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/07/18/spring-boot-step-by-step-three/">





  <title>【第五章】一步一步学习SpringBoot2——SpringBoot事务支持 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/07/18/spring-boot-step-by-step-three/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第五章】一步一步学习SpringBoot2——SpringBoot事务支持</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-18T17:24:24+08:00">
                2019-07-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Springboot/" itemprop="url" rel="index">
                    <span itemprop="name">Springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为《一步一步学习Spring Boot 2》的第五章的学习笔记，主要内容为SpringBoot事务支持</p>
<p>本书博客地址：<a href="https://blog.csdn.net/huangwenyi1010?t=1" target="_blank" rel="noopener">https://blog.csdn.net/huangwenyi1010?t=1</a></p>
<p>本文部分内容和图片引用自：<a href="https://blog.csdn.net/huangwenyi1010/article/details/82810252" target="_blank" rel="noopener">https://blog.csdn.net/huangwenyi1010/article/details/82810252</a></p>
<p>源代码地址：<a href="https://gitee.com/aiolos123/springboot-step-by-step" target="_blank" rel="noopener">https://gitee.com/aiolos123/springboot-step-by-step</a></p>
<a id="more"></a>
<h1 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h1><ol>
<li>事务一般都是加在服务层</li>
<li>Spring Boot开启事务很简单，只需要一个注解@Transactional 就可以了。</li>
<li>在Spring Boot中已经默认对JPA、JDBC、Mybatis开启了事务，引入它们依赖的时候，事务就默认开启了。</li>
<li>@Transactional注解在类上，意味着此类的所有public方法都是开启事务的。</li>
</ol>
<h1 id="事务简介"><a href="#事务简介" class="headerlink" title="事务简介"></a>事务简介</h1><ol>
<li>事务管理是企业级应用程序开发中必不可少的技术，用来确保数据的完整性和一致性。</li>
<li>Spring在不同的事务管理API之上定义了一个抽象层PlatformTransactionManager。而应用程序开发人员不必了解底层的事务管理API，就可以使用Spring的事务管理机制。</li>
<li>Spring并不直接管理事务，而是提供了许多内置事务管理器实现，常用的有：DataSourceTransactionManager、JdoTransactionManager、JpaTransactionManager、以及HibernateTransactionManager等等。</li>
<li>声明式事务管理是指将事务管理代码从业务方法中分离出来，以声明的方式来实现事务管理。大多数情况下声明式事务管理比编程式事务管理更好用。</li>
<li>Spring通过Spring AOP框架支持声明式事务管理。</li>
</ol>
<h2 id="Spring声明式事务"><a href="#Spring声明式事务" class="headerlink" title="Spring声明式事务"></a>Spring声明式事务</h2><blockquote>
<p>Spring配置文件中关于事务配置总是由三个组成部分，分别是DataSource、TransactionManager和代理机制这三部分。无论哪种配置方式，一般变化的只是代理机制这部分。DataSource和TransactionManager这两部分只会根据数据访问方式有所变化，比如使用Hibernate进行数据访问时，DataSource实现为SessionFactory，TransactionManager的实现为HibernateTransactionManager。</p>
</blockquote>
<p>Spring声明式事务配置提供五种方式，而<strong>基于 Annotation 注解方式</strong>目前比较流行，所以这里只简单介绍基于注解方式配置Spring声明式事务————————使用@Transactional注解在类或者方法上表明该类或者方法需要事务支持。被注解的类或者方法被调用时，Spring开启一个新的事务，当方法正常运行时，Spring会提交这个事务。</p>
<p>具体例子如下：</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// @Transactional注解来自org.springframework.transaction.annotation。</span></span><br><span class="line"><span class="comment">// Spring提供了@EnableTransactionManagement注解在配置类上来开启声明式事务的支持。</span></span><br><span class="line"><span class="comment">// 使用@EnableTransactionManagement后，Spring容器会自动扫描注解@Transactional的方法和类。</span></span><br><span class="line"><span class="meta">@Transactional</span></span><br><span class="line"><span class="keyword">public</span> <span class="function">AyUser <span class="title">updateUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//执行数据库操作</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="事务传播行为"><a href="#事务传播行为" class="headerlink" title="事务传播行为"></a>事务传播行为</h2><blockquote>
<p>事务传播行为：当事务方法被另一个事务方法调用时，必须指定事务应该如何传播。</p>
</blockquote>
<p>例如：方法可能继续在现有事务中运行，也可能开启一个新事务，并在自己的事务中运行。事务的传播行为可以在@Transactional的属性中指定。Spring定义了7种传播行为，具体如下图所示。<br><img src="/blog/images/20190724183626414.jpg" alt="事务传播行为"></p>
<pre><code>@Transactional可以通过propagation属性定义事务行为，属性值分别为：
REQUIRED、SUPPORTS、MANDATORY、REQUIRES_NEW、NOT_SUPPORTED、NEVER以及NESTED，
分别对应上图中的内容。 </code></pre><p>还可以通过timeout属性设置事务过期时间，通过readOnly指定当前事务是否是只读事务，通过rollbackFor（noRollbackFor）指定那个或者那些异常可以引起（或不可以引起）事务回滚。</p>
<h2 id="事务隔离级别"><a href="#事务隔离级别" class="headerlink" title="事务隔离级别"></a>事务隔离级别</h2><blockquote>
<p>事务隔离级别：定义了一个事务可能受其它并发事务影响的程度。</p>
</blockquote>
<p>在典型的应用程序中，多个事务并发运行，经常会操作相同的数据来完成各自的任务。并发，虽然是必须的，可是会导致许多问题。</p>
<p><strong>并发事务所导致的问题</strong>可以分为以下三类：<br>① 脏读(Dirty reads)：脏读发生在一个事务读取了另一个事务改写但尚未提交的数据。如果改写在稍后被回滚了，那么第一个事务获取的数据就是无效的。<br>② 不可重复读(Nonrepeatable read)：不可重复读发生在一个事务执行相同的查询两次或两次以上，但是每次都得到不同的数据时。这通常是因为另一个并发事务在两次查询期间更新了数据。<br>③ 幻读(Phantom read)：幻读与不可重复读类似。它发生在一个事务(T1)读取了几行数据，接着另一个并发事务(T2)插入了一些数据时。在随后的查询中，第一个事务(T1)就会发现多了一些原本不存在的记录。<br>针对这些问题，Spring提供了五种事务的隔离级别，具体如下：<br><img src="/blog/images/20190724184038864.jpg" alt="事务隔离级别"></p>
<pre><code>@Transactional可以通过isolation属性定义隔离级别，
属性值分别为：DEFAULT、READ_UNCOMMITTED、READ_COMMITTED、REPEATABLE_READ以及SERIALIZABLE。
分别对应上图中的内容。</code></pre><p>还可以通过timeout属性设置事务过期时间，通过readOnly指定当前事务是否是只读事务，通过rollbackFor（noRollbackFor）指定那个或者那些异常可以引起（或不可以引起）事务回滚。</p>
<h1 id="Spring-Boot事务支持"><a href="#Spring-Boot事务支持" class="headerlink" title="Spring Boot事务支持"></a>Spring Boot事务支持</h1><blockquote>
<p>Spring Boot开启事务很简单，只需要一个注解@Transactional 就可以了，<br>因为在Spring Boot中已经默认对JPA、JDBC、Mybatis开启了事务，引入它们依赖的时候，事物就默认开启。<br>当然，如果你需要用其它的ORM框架，比如BeatlSQL，就需要自己配置相关的事物管理器。</p>
</blockquote>
<pre><code>Spring Boot用于配置事务的类为TransactionAutoConfiguration，
此配置类依赖于JtaAutoConfiguration和DataSourceTransactionManagerAutoConfiguration，
具体查看源码可知，DataSourceTransactionManagerAutoConfiguration开启了对声明式事务的支持，
所以在Spring Boot中，无须显示使用@EnableTransactionManagement开启事务。</code></pre><h2 id="类级别事务"><a href="#类级别事务" class="headerlink" title="类级别事务"></a>类级别事务</h2><p>在之前的代码中，Spring Boot中已经集成了Spring Data JPA。<br>JpaRepository接口是不开启事务的，而SimpleJapRepository默认是开启事务的，所以我们需要手工给AyUserRepository添加事务。<br>AyUserRepository类中的方法是在服务层类AyUserServiceImpl中被使用，而<strong>事务一般都是加在服务层</strong>，因此我们可以在AyUserServiceImpl类上添加@Transactional注解来开启事务。</p>
<p>AyUserServiceImpl类开启事务的代码如下：</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//@Transactional注解在类上，意味着此类的所有public方法都是开启事务的。</span></span><br><span class="line"><span class="variable">@Transactional</span></span><br><span class="line"><span class="variable">@Service</span></span><br><span class="line">public class AyUserServiceImpl implements IAyUserService &#123;</span><br><span class="line"></span><br><span class="line">    <span class="selector-tag">private</span> <span class="selector-tag">AyUserRepository</span> <span class="selector-tag">ayUserRepository</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//省略代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="方法级别事务"><a href="#方法级别事务" class="headerlink" title="方法级别事务"></a>方法级别事务</h2><p>@Transactional除了可以注解在类上，还可以注解到方法上面。当注解在类上的时候意味着此类的所有public方法都是开事务的。<br>如果类级别和方法级别同时使用了@Transactional注解，则使用方法级别注解覆盖类级别注解。</p>
<p>我们可以给AyUserServiceImpl类中的save()方法添加事务，同时在save完成之后抛NullPointException异常，查看数据是否可以回滚。<br>具体代码如下：</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyUserServiceImpl</span> <span class="keyword">implements</span> <span class="title">IAyUserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AyUserRepository ayUserRepository;</span><br><span class="line">	   </span><br><span class="line">    <span class="comment">//注解在方法上</span></span><br><span class="line">    <span class="meta">@Transactional</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function">AyUser <span class="title">save</span><span class="params">(AyUser ayUser)</span> </span>&#123;</span><br><span class="line">        AyUser saveUser =  ayUserRepository.save(ayUser);</span><br><span class="line">        <span class="comment">//出现空指针异常</span></span><br><span class="line">        String <span class="keyword">error</span> = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">error</span>.split(<span class="string">"/"</span>);</span><br><span class="line">        <span class="keyword">return</span> saveUser;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="单元测试"><a href="#单元测试" class="headerlink" title="单元测试"></a>单元测试</h2><p>我们在测试类MySpringBootApplicationTests中添加测试方法，具体代码如下</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">void</span> <span class="title">testTransaction</span><span class="params">()</span></span>&#123;</span><br><span class="line">	AyUser ayUser = <span class="keyword">new</span> AyUser();</span><br><span class="line">	ayUser.setId(<span class="string">"3"</span>);</span><br><span class="line">	ayUser.setName(<span class="string">"阿华"</span>);</span><br><span class="line">	ayUser.setPassword(<span class="string">"123"</span>);</span><br><span class="line">	ayUserService.save(ayUser);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>执行添加了@Transactional注解的方式，由于方法save保持数据时候，出现空指针，事务执行了回滚操作，数据未添加到数据库中。<br><img src="/blog/images/20190725054936997.jpg" alt="事务起了作用"></li>
<li>如果我们把AyUserServiceImpl类上的@Transactional注解和save方法上的@ Transactional注解全部注释掉，再次执行testTransaction（）单元测试用例，查询数据库，发现事务不再起效，数据已经添加到数据库中。<br><img src="/blog/images/20190725055301760.jpg" alt="事务隔离级别"></li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/springboot-step-by-step/" rel="tag"># springboot-step-by-step</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/07/18/spring-boot-step-by-step-two-two/" rel="next" title="【第四章】一步一步学习SpringBoot2——集成Thymeleaf">
                <i class="fa fa-chevron-left"></i> 【第四章】一步一步学习SpringBoot2——集成Thymeleaf
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/07/18/spring-boot-step-by-step-three-two/" rel="prev" title="【第六章】一步一步学习SpringBoot2——使用过滤器Filter和监听器Listener">
                【第六章】一步一步学习SpringBoot2——使用过滤器Filter和监听器Listener <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#注意事项"><span class="nav-number">1.</span> <span class="nav-text">注意事项</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#事务简介"><span class="nav-number">2.</span> <span class="nav-text">事务简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring声明式事务"><span class="nav-number">2.1.</span> <span class="nav-text">Spring声明式事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务传播行为"><span class="nav-number">2.2.</span> <span class="nav-text">事务传播行为</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务隔离级别"><span class="nav-number">2.3.</span> <span class="nav-text">事务隔离级别</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Spring-Boot事务支持"><span class="nav-number">3.</span> <span class="nav-text">Spring Boot事务支持</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#类级别事务"><span class="nav-number">3.1.</span> <span class="nav-text">类级别事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方法级别事务"><span class="nav-number">3.2.</span> <span class="nav-text">方法级别事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单元测试"><span class="nav-number">3.3.</span> <span class="nav-text">单元测试</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
